﻿using System;
using System.Linq;
using System.Runtime.Loader;
using Microsoft.Extensions.DependencyInjection;

namespace Solution.Comm.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static void AddAssembly(this IServiceCollection services, string assemblyName, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services) + "为空");

            if (string.IsNullOrEmpty(assemblyName))
                throw new ArgumentNullException(nameof(assemblyName) + "为空");

            var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new System.Reflection.AssemblyName(assemblyName));

            if (assembly == null)
                throw new DllNotFoundException(nameof(assembly) + ".dll不存在");

            var types = assembly.GetTypes();
            var list = types.Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType).ToList();
            if (list.Count <= 0)
                return;
            foreach (var type in list) {
                var interfacesList = type.GetInterfaces();
                if (interfacesList == null || !interfacesList.Any())
                    continue;
                var inter = interfacesList.First();
                switch (serviceLifetime) {
                    case ServiceLifetime.Scoped:
                        services.AddScoped(inter, type);
                        break;

                    case ServiceLifetime.Singleton:
                        services.AddScoped(inter, type);
                        break;

                    case ServiceLifetime.Transient:
                        services.AddTransient(inter, type);
                        break;
                }
            }
        }
    }
}